package com.cs.config;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Configuration
public class Oauth2FeignInterceptor implements RequestInterceptor {
    /**
     * 这个方法就是拦截后的方法 对每次远程调用都进行拦截
     * 主要帮我们做token的传递 因为每个资源服务器都需要token
     * 1 浏览器携带token进行远程调用
     * 2应用本事自发的请求
     * 3支付宝的回调
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(!ObjectUtils.isEmpty(requestAttributes)){//说明有请求
            HttpServletRequest request = requestAttributes.getRequest();
            String authorization = request.getHeader("Authorization");
            if(!StringUtils.isEmpty(authorization)){
                //传递给下一个资源服务器
                requestTemplate.header("Authorization",authorization);
                return;
            }
        }
        requestTemplate.header("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIl0sImV4cCI6Mzc2NDU3ODUwMCwianRpIjoiNTE1OTk4NzctMDAxNS00MmMwLTk3YWYtOGFhYmZlMzI4ZDlhIiwiY2xpZW50X2lkIjoiY2xpZW50In0.FNFnSKqHsD8P8Y2h_OmJmEAsOaa7G5hb4C-C0h54vMSF4b289KVbIX4al6kkdn8MuOPDlUM3qx-PXW4m18PTbSOW7KEiTOooJsajzind54bu3fkZrqhcLaDbAdjwd7ZQjiIAmwzYo4Lm-X7_uFPejlI5yqcWXDlXWhfa9if0aYEZCH-QcAnOq1wmibiueCNKV-axK-AUufxr4GGOWBtGvSy-iWsfiq8XHiB21hRF49eKmayuc-aQNszXOzobSSo_PqF-31I1AImwoSpr6N4BV5e6ZpIN3dI020KKlaJdWc9L__gbqBaFw2GHQlVT_4mYZQvzB0WjfArmwl2m4yvvww");
    }
}
